package com.tongserver.huanxin;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class JsonDemo {
	public static void main(String[] args) {
		JsonDemo jsonDemo = new JsonDemo();
		// ElectSet elec = jsonDemo.findElectSet("src/test.json");
		List<ElectSet> electsets = jsonDemo.readJSON("src/test.json","electset");
		//System.out.println(electsets.size());
		for(int i=0;i<electsets.size();i++){
			System.out.println(electsets.get(i).getIsReadDB()+";"+electsets.get(i).getStartTime()+";"+electsets.get(i).getXuenian());
		}
	}

	// 读文件，返回字符串
	public String ReadFile(String path) {
		File file = new File(path);
		BufferedReader reader = null;
		String laststr = "";
		try {
			// System.out.println("以行为单位读取文件内容，一次读一整行：");
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				System.out.println("line " + line + ": " + tempString);
				laststr = laststr + tempString;
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return laststr;
	}

	/*
	 * 取出文件内容，填充对象
	 */
	public ElectSet findElectSet(String path) {
		ElectSet electset = new ElectSet();
		String sets = ReadFile(path);// 获得json文件的内容
		JSONObject jo = JSONObject.fromObject(sets);// 格式化成json对象
		electset.setXueqi(jo.getString("xueqi"));
		electset.setXuenian(jo.getString("xuenian"));
		electset.setStartTime(jo.getString("startTime"));
		electset.setEndTime(jo.getString("endTime"));
		electset.setMenshu(jo.getInt("menshu"));
		electset.setIsReadDB(jo.getString("isReadDB"));
		return electset;
	}

	// 把json格式的字符串写到文件
	public void writeFile(String filePath, String sets) throws IOException {
		FileWriter fw = new FileWriter(filePath);
		PrintWriter out = new PrintWriter(fw);
		out.write(sets);
		out.println();
		fw.close();
		out.close();
	}

	public List<ElectSet> readJSON(String path,String key) {
		String data = ReadFile(path);
		System.out.println(data);
		JSONObject jsonObj = JSONObject.fromObject(data);
		// 得到ElectSet集合
		JSONArray arrayElectSet = jsonObj.getJSONArray(key);
		List<ElectSet> list = new ArrayList<ElectSet>();
		for (int i = 0; i < arrayElectSet.size(); i++) {
			ElectSet b = (ElectSet) JSONObject.toBean(
					(JSONArray.fromObject(arrayElectSet.toString()).getJSONObject(i)),
					ElectSet.class);
			list.add(b);
		}
		//得到MyDemo对象
		System.out.println("myDemo:"+jsonObj.get("myDemo"));
		return list;
	}
}